# coding=utf-8
import hashlib, base64, random, string

class UserLibs() :

    @staticmethod
    def genePassword(pwd, salt):
        """
        密码加密
        :param pwd:
        :param salt:
        :return:
        """
        str = "%s-%s" % ( base64.encodebytes( pwd.encode("utf-8") ), salt) #密码base64加密 + 随机字符串
        return UserLibs.encrypt(str)

    @staticmethod
    def geneAuthCode( user_info ):
        """
        登录cookie加密
        :param user_info:
        :return:
        """
        str = "%s-%s-%s-%s" % (user_info.uid, user_info.login_name, user_info.login_pwd, user_info.login_salt)
        return UserLibs.encrypt(str)

    @staticmethod
    def encrypt(str) :
        """
        加密
        :param str:
        :return:
        """
        m = hashlib.md5()
        m.update(str.encode("utf-8"))  # 密码MD5加密
        return m.hexdigest()

    @staticmethod
    def geneSalt(length = 16):
        keylist = [ random.choice( string.ascii_letters + string.digits ) for i in range( length ) ]
        return "".join( keylist )